
#import "DatabaseManager.h"

@implementation DatabaseManager

// DB 관련변수
static sqlite3* database;
static BOOL dbState;

// 데이터베이스 초기화
+ (void) connectDatabse {
	
	// database 접속 관련 변수
	BOOL success;
	NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"ZinDataBase.sqlite"];    
	NSString* dbPath = [documentsDirectory stringByAppendingPathComponent:@"ZinDataBase.sqlite"];
	
	// Document 폴더에 database 유무 확인
    success = [fileManager fileExistsAtPath:dbPath];	
	
	// Resources 에서 database 카피
	if (!success) {
		success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
	}
	if (!success) {
//		NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
        NSLog(@"Database failed");
        return;
	}
	
	if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK){ 
		dbState = YES;
	}
}

+ (void) closeDatabse {
	sqlite3_close(database);
}

// 리스트
+ (NSMutableArray *) customerList {
	
    [self connectDatabse];
	// 셀렉트
	NSMutableArray* list = [NSMutableArray array];
	
    if (dbState == YES) {
        
//		NSString* query = @"SELECT C_time, C_name,C_phone,C_mail,C_expanse,C_memo,C_item,C_imgName FROM customerTb";
        NSString* query = @"SELECT * FROM customerTb";
//        const char* sqlStatement = "SELECT * FROM customerTb";
//		NSLog(@"%@", sqlStatement);
		
		const char *sql = [query cStringUsingEncoding:1];
		
        sqlite3_stmt *statement;
		
        if (sqlite3_prepare_v2(database,  sql, -1, &statement, NULL) == SQLITE_OK) {  			
			
            while (sqlite3_step(statement) == SQLITE_ROW) {		
				
				NSMutableDictionary* dic = [NSMutableDictionary dictionary];
                [dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)] forKey:@"seq"];
                [dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] forKey:@"C_date"];
				[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)] forKey:@"C_time"];
				[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)] forKey:@"C_name"];
				[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 4)] forKey:@"C_phone"];
                [dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 5)] forKey:@"C_mail"];
				[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 6)] forKey:@"C_expanse"];
				[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 7)] forKey:@"C_memo"];
                [dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 8)] forKey:@"C_item"];
				[dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 9)] forKey:@"C_wallPaperImgName"];
                [dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 10)] forKey:@"C_FlooringImgName"];

				[list addObject:dic];
			}     
        }
        sqlite3_finalize(statement);
    }
    [self closeDatabse];
	return list;
}

// 리스트
+ (NSMutableArray *) selectedColorList:(NSInteger)colorCode category:(NSInteger)categoryCode
{
     [self connectDatabse];
	NSMutableArray* list = [NSMutableArray array];
	
    if (dbState == YES) {
        NSString* str = [self searchColorName:colorCode];
                                
		NSString* query1 = @"SELECT * FROM wallpaperTb WHERE W_category ='";
        NSString* query2 = [NSString stringWithFormat:@"%d' AND W_color LIKE '%%", categoryCode];
        NSString* query3 = [NSString stringWithFormat:@"%@%%'", str];
        NSString* query = [NSString stringWithFormat:@"%@%@%@", query1, query2, query3];
        
		
		NSLog(@"%@", query);
	
		const char *sql = [query cStringUsingEncoding:1];
//		
        sqlite3_stmt *statement;
		
        if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {  			
			
           while (sqlite3_step(statement) == SQLITE_ROW) {
               NSMutableDictionary* dic = [NSMutableDictionary dictionary];
               [dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] forKey:@"W_model"];
               [dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)] forKey:@"W_name"];
               [dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)] forKey:@"W_img_thumb"];
               [dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 4)] forKey:@"W_img_original"];
               [dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 5)] forKey:@"W_description"];
               [dic setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 9)] forKey:@"W_category"];
               [list addObject:dic];
				
			}     
        }
        sqlite3_finalize(statement);
    }
    [self closeDatabse];
	return list;
}

////// Util ///// 
+(NSArray *) spliteString:(NSString*)_words 
{
    NSArray* list = [NSArray array];
    
    list = [_words componentsSeparatedByString:@"|"];
    
    return list;
    
}

+ (NSString*) searchColorName:(NSInteger)code
{
     NSMutableArray* colorList = [[NSMutableArray alloc] init];
    [colorList addObject:@"gold"];
    [colorList addObject:@"gray"];
    [colorList addObject:@"green"];
    [colorList addObject:@"red"];
    [colorList addObject:@"beige"];
    [colorList addObject:@"black"];
    [colorList addObject:@"blue"];
    [colorList addObject:@"brown"];
    [colorList addObject:@"silver"];
    [colorList addObject:@"lightgreen"];
    [colorList addObject:@"yellow"];
    [colorList addObject:@"ivory"];
    [colorList addObject:@"wine"];
    [colorList addObject:@"khaki"];
    [colorList addObject:@"cobalt"];
    [colorList addObject:@"purple"];
    [colorList addObject:@"pink"];
    [colorList addObject:@"white"];
    [colorList addObject:@"etc"];
    
    NSString* strColor = [colorList objectAtIndex:code];
    
    return strColor;
}

- (void)dealloc {
	[DatabaseManager closeDatabse];
	[super dealloc];
}

@end
